import os

from pyx_package.script import BaseBehavior
from pyx_package.ps_paramete import PsParameter
PYX_MODULE_NAME = "文件夹解析-单文件迭代"

class ScriptBehavior(BaseBehavior):

    def __init__(self) -> None:
        super().__init__()
        
        self.SetExeMode("iter")

        self.p_path = self.CreateParam(
            "path", "文件夹路径", PsParameter.Input, str)
            
        #跳过的路径
        self.p_skip_path = self.CreateParam(
            "skip_path", "跳过的文件夹", PsParameter.Input, list)
        self.p_skip_path.value = []

        self.p_file_path = self.CreateParam(
            "file_path", "输出列表", PsParameter.Output, list,  [])

    def FirstStep(self):
        self.p_path.value = self.PathFormat(self.p_path.value)
        
    def DoStep(self):

        #如果路径不存在，就跳过
        if not os.path.isdir(self.p_path.value):
            self.Debug("path not exist:" + self.p_path.value, "error")
            return 
    
        self.AnalysisDir(self.p_path.value)

    def IsSkip(self, path):
        '''
            判断一个路径是否跳过
        '''
        
        for s_path in self.p_skip_path.value:
            if self.PathFormat(s_path) in self.PathFormat(path):
                return True
                
        return False
        
    def AnalysisDir(self, path):
        '''
            解析文件夹
        '''

        #如果是过滤的文件夹，则跳过
        if self.IsSkip(path):
            return 
            
        parent, dirnames, filenames = os.walk(path).__next__()

        for file_name in filenames: 
            file_data = parent + "/" + file_name
            self.p_output_list.value.append(file_data)

        for dir_name in dirnames:
            self.AnalysisDir(self.PathFormat(parent) + "/" + dir_name)

    
    def PathFormat(self, path: str):
        '''
            将给定路径进行格式化
                1. 将所有的\\ 替换为/
                2. 删除最后一位的/
        '''
        path = path.replace("\\", "/")
        path = path.strip().rstrip("/")

        return path
